package com.hns.can.mainte.web;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hns.can.base.entity.SysUserEntity;
import com.hns.can.common.domain.GridPage;
import com.hns.can.common.entity.BaseEntity;
import com.hns.can.common.web.BaseController;
import com.hns.can.mainte.entity.CommLogFileRcdEntity;
import com.hns.can.mainte.service.EngineManageService;
import com.hns.can.mainte.service.LoadFileService;
import com.hns.can.mainte.vo.EngineRunStatusParamVo;
import com.hns.can.mainte.vo.LoadFileParamVo;
import com.hns.can.master.entity.BaseCarInfoEntity;
import com.hns.frame.enumrate.MsgType;
import com.hns.frame.exception.BusinessException;
import com.hns.frame.mybatis.Pagination;
import com.hns.tool.export.ExportUtil;
import com.hns.tool.pub.DateTool;
import com.hns.tool.pub.FTPUtils;
import com.hns.tool.pub.PubUtil;
import com.hns.tool.pub.UtilConfig;

/**
 * 发动机Controller
 * @author:zhangzq
 * @email:
 * @version Revision 2.0.0
 */
@Controller
@RequestMapping("/engineManage")
public class EngineManageController extends BaseController{	
	
	final private String[] headerNames={"车牌号","记录时间", "车速", "转速", "进气压力(mPa)", "进气温度(℃)", "氧浓度(%)", "油门踏板", "电子节气门开度", "水温(℃)", "燃油温度(℃)", "机油温度(℃)",
	        "机油压力(mPa)", "天然气温度(℃)", "天然气压力(mPa)", "扭矩百分比(%)", "最大参考扭矩", "总能耗", "瞬时能耗", "仓温(℃)"};
	final private String[] headerFields={"licPltNo","rcrdTime", "gpsSpdOfMotVhi", "engiRtteSpd", "airAdmissionPrs", "engiAirAdmissionTept", "oxygenConcen", "engiActualAclt",  "electThroOpe", "engiWteTpte",
        "engiFlOilTept","engnOilTept", "engiEngnOilPrs", "nalGasTept", "nalGasPrs", "torqPetg", "maxRefrTorq", "engiTotalFuelCsutNum", "instFuelCsut","wahTept"};
   	
    @Autowired
    private EngineManageService engineManageService;
    
    @Autowired
	private LoadFileService loadFileService;

	/**
	 * 分页查询发动机运行状态数据
	 * @param conditionVo
	 * @return
	 * @throws Exception
	 * @author:zhangzq
	 * @email:
	 */
    @RequestMapping("/searchEngineRunStatusPage")
    @ResponseBody
    public Object searchEngineRunStatusPage(EngineRunStatusParamVo conditionVo) throws Exception {    	
        SysUserEntity user = this.getCurrentUser().getUser();
        conditionVo.setCorpId(user.getCorpId());
        conditionVo.setDriverRelTableName("T_COMM_VEHICLE_OPRT_ST_INFO");
        Pagination page = engineManageService.searchEngineRunStatusPage(conditionVo);
        GridPage grid = new GridPage(page);
        return this.getReturnResult(grid);
    }
    
    /**
     * 导出发动机运行状态Excel文件
     * @param conditionVo
     * @throws Exception
     * @author:zhangzq
     * @email:
     */
    @RequestMapping("/exportEngineRunStatus2Excel")
    public void exportEngineRunStatus2Excel(EngineRunStatusParamVo conditionVo,HttpServletResponse response) throws Exception {
        List<BaseEntity> list = getEngineRunStatusList(conditionVo);
        ExportUtil.exportFiles(Arrays.asList(headerNames), Arrays.asList(headerFields), list, response, "excel", "EngineRunStatus"+DateTool.getCurrentSysDate("yyyyMMddHHmmss"), "发动机运行状态");
    }
    
    /**
     * 导出发动机运行状态Pdf文件
     * @param conditionVo
     * @throws Exception
     * @author:zhangzq
     * @email:
     */
    @RequestMapping("/exportEngineRunStatus2Pdf")
    public void exportEngineRunStatus2Pdf(EngineRunStatusParamVo conditionVo,HttpServletResponse response) throws Exception {
        List<BaseEntity> list = getEngineRunStatusList(conditionVo);
        ExportUtil.exportFiles(Arrays.asList(headerNames), Arrays.asList(headerFields), list, response, "pdf", "EngineRunStatus"+DateTool.getCurrentSysDate("yyyyMMddHHmmss"), "发动机运行状态");
    }
    
    /**
     * 获取发动机运行状态，用于导出
     * @param conditionVo
     * @return
     * @throws Exception
     * @author:zhangzq
     * @email:
     */
    private  List<BaseEntity> getEngineRunStatusList(EngineRunStatusParamVo conditionVo) throws Exception {
    	SysUserEntity user = this.getCurrentUser().getUser();
        conditionVo.setCorpId(user.getCorpId());
        conditionVo.setCorpId(user.getCorpId());
        conditionVo.setDriverRelTableName("T_COMM_ENGI_ST_INFO");        
        List<BaseEntity> list = engineManageService.searchEngineRunStatusList(conditionVo);
        if(PubUtil.isEmpty(list)){
            throw new BusinessException(MsgType.WARN.getFlag(), "没有数据导出！");
        }
        return list;
    }

    // DOIT: 2016-12-23 外特性曲线图、发动机功率图
    
    /**
     * 获取发动机运行状态，用于图表
     * @param conditionVo
     * @return
     * @throws Exception
     * @author:zhangzq
     * @email:
     */
    @RequestMapping("/getEngineRunStatusListForGraph")
    @ResponseBody
    public Object getEngineRunStatusListForGraph(EngineRunStatusParamVo conditionVo ) throws Exception {
    	SysUserEntity user = this.getCurrentUser().getUser();
        conditionVo.setCorpId(user.getCorpId());
        List<BaseEntity> list = engineManageService.getEngineRunStatusListForGraph(conditionVo);
        return this.getReturnResult(list);
    }
    
    @RequestMapping("/getEngineFile")
    public void getEngineFile(String[] fileNames,HttpServletResponse response) throws Exception {
    	
    	for(String fileName:fileNames){
    		 FTPClient ftpClient = FTPUtils.getInstance().getClient();
    	     InputStream inputStream = ftpClient.retrieveFileStream( UtilConfig.getString("ftp_accident_path") + fileName);
//            String targetPath = FileUploadUtil.getWebRoot(request) + "\\accident" ;
//            File tempFile =FtpUtil.download("ftp://admin:hns@59.57.240.218:21/hnsfiles/upload/communimodel/accident/"+fileName, targetPath, 2048);
    		OutputStream os = response.getOutputStream();
            if(inputStream!=null){
                try {
		            response.reset();
		            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
		            response.setContentType("application/octet-stream; charset=utf-8");
		            int bytesRead = 0;
		            byte[] buffer = new byte[8192];
		            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
		            os.write(buffer, 0, bytesRead);
		            }
		            os.flush();
		        } finally {
		            if (os != null) {
		                os.close();
		            }
		        }
            }
    	}
    }
    
    //-----------------------------------------------------------------------------------------------
  
     /**
      * 查询下载的文件明细
      * @param entity
      * @return
      * @throws Exception
      * @author:zhangzq
      * @email:
      */
      @RequestMapping("/searchLoadFileRcd")
      @ResponseBody
      public Object searchLoadFileRcd(LoadFileParamVo entity) throws Exception {
	      checkLoadFileParam(entity);
	      List<CommLogFileRcdEntity> commLogFileRcdEntityList=null;
	      try {
			loadFileService.saveLoadFile(entity);
			commLogFileRcdEntityList = loadFileService.getCommLogFileRcdByTimeList(entity);
		  } catch (Exception e) {
			throw new BusinessException(MsgType.ERROR.getFlag(), e.getMessage());
		  }
  		  if(commLogFileRcdEntityList==null){
  			throw new BusinessException(MsgType.ERROR.getFlag(),"当前时间区间没有相关的数据!");
  		  }
  		return this.getReturnResult(commLogFileRcdEntityList);
      }
      
      /**
       * 下载选中的文件
       * @param entity
       * @return
       * @throws Exception
       * @author:zhangzq
       * @email:
       */
      @RequestMapping("/loadFiles")
      @ResponseBody
      public Object loadFiles(LoadFileParamVo entity) throws Exception {
          try {
              String ftpEngInfoPath = UtilConfig.getString("ftp_engInfo_path");
              entity.setFtpUrl(ftpEngInfoPath);
              loadFileService.loadFiles(entity);
              return this.getReturnResult(null);
          } catch (Exception e) {
              throw new BusinessException(MsgType.ERROR.getFlag(), e.getMessage());
          }
      }
      
      /**
       * 文件下载状态查询
       * @param entity
       * @return
       * @throws Exception
       * @author:zhangzq
       * @email:
       */
      @RequestMapping("/getLoadFileSt")
      @ResponseBody
      public Object searchAccFileSt(LoadFileParamVo entity) throws Exception {
        	List<CommLogFileRcdEntity> commLogFileRcdEntityList=null;
      		try {
      			if(PubUtil.isNotEmpty(entity.getFileNames())){
    	  			String devId=loadFileService.getDevId(entity);
    	  			entity.setDevId(devId);
    	  			commLogFileRcdEntityList = loadFileService.getCommLogFileRcdByFileList(entity);
      			}
      		} catch (Exception e) {
      			throw new BusinessException(MsgType.ERROR.getFlag(), e.getMessage());
      		}
      		return this.getReturnResult(commLogFileRcdEntityList);
      }
      
      /**
       * 参数值校验
       * @param entity
       * @return
       * @author:zhangzq
       * @email:
       */
      private void  checkLoadFileParam(LoadFileParamVo entity) {
       	 if(PubUtil.isEmpty(entity.getCarIds())||entity.getCarIds().length>1){
                throw new BusinessException(MsgType.ERROR.getFlag(), "有且仅能选择一辆车！");
            }
            if(PubUtil.isEmpty(entity.getBeginTime())||PubUtil.isEmpty(entity.getEndTime())){
                throw new BusinessException(MsgType.ERROR.getFlag(), "起始时间和结束时间不允许为空！");
            }
       }
      
      /**
       * 
       * @param carId
       * @return
       * @throws Exception
       * @author:zhangzq
       * @email:
       */
      @RequestMapping("/getEngineInfo")
      @ResponseBody
      public Object getEngineInfo(String carId) throws Exception{
          BaseCarInfoEntity entity = engineManageService.getEngineInfo(carId);
          return this.getReturnResult(entity);
      }
}

